#include "groundweatherstationform.h"
#include "ui_groundweatherstationform.h"
#include "../../protocol/groundweatherstationprotocol.h"
#include "../../dataBase/connection.h"
#include "../gloab/globalobserver.h"
#include "../gloab/mymessagebox.h"
#include "QsLog/QsLog.h"

#include <QSerialPortInfo>
#include <QUuid>
#include <QMessageBox>

GroundWeatherStationForm::GroundWeatherStationForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::GroundWeatherStationForm)
    , m_port(new QSerialPort(this))
{
    ui->setupUi(this);
    formInit();
    connect(this, &GroundWeatherStationForm::Sig_DeviceGroundWeatherStationProtocol, GlobalObserver::getInstance(), &GlobalObserver::Sig_GroundWeatherStationProtocol);
}

GroundWeatherStationForm::~GroundWeatherStationForm()
{
    delete ui;
}

void GroundWeatherStationForm::formInit()
{
    //刷新按钮
    connect(ui->meteSerialPortFleshbtn, &QPushButton::clicked, this, [=](){
        ui->meteSerialPortcbx->clear();
        QList<QSerialPortInfo> info_list = QSerialPortInfo::availablePorts();
        QStringList portList;
        QListIterator<QSerialPortInfo> iter(info_list);
        iter.toFront();
        while (iter.hasNext()) {
            QSerialPortInfo info = iter.next();
            portList.append(info.portName());
        }
        if(portList.empty()){
            ui->meteSerialPortcbx->addItem("没有串口");
        }else{
            ui->meteSerialPortcbx->addItems(portList);
        }
    } );

    //连接按钮
    connect(ui->meteOpenClosebtn, &QPushButton::clicked, this, [=](){
        if(ui->meteOpenClosebtn->text() == "连接"){
            if(ui->meteSerialPortcbx->currentText().isEmpty()){
                MyMessageBox msgBox(this, MsgBoxType_Info, "串口未设置");
                msgBox.exec();
                return ;
            }
            QString port = ui->meteSerialPortcbx->currentText();

            bool bl = openDevice(port);
            if(!bl){
                QLOG_WARN()<<CALLPOINTINFO<<"地面气象站打开失败";
            }
            else{
                /*启动的时候清空一下之前所有的点*/
                ui->meteOpenClosebtn->setText("断开");
            }
        }else{
            closeDevice();
            ui->meteOpenClosebtn->setText("连接");
        }
    });
}

bool GroundWeatherStationForm::openDevice(QString portName)
{
    m_port->setPortName(portName);
    m_port->setBaudRate(9600);
    m_port->setDataBits(QSerialPort::Data8);
    m_port->setStopBits(QSerialPort::OneStop);
    m_port->setParity(QSerialPort::NoParity);
    m_port->setFlowControl(QSerialPort::NoFlowControl);
    m_port->setReadBufferSize(4096);
    if(m_port->open(QSerialPort::ReadWrite)){
        qDebug()<<"打开成功";
        connect(this->m_port, &QSerialPort::errorOccurred, this, [=](QSerialPort::SerialPortError err){
            qDebug()<<"错误信息 : "<<this->m_port->errorString();
        });
        connect(this->m_port, &QSerialPort::readyRead, this, [=](){
            if(this->m_port->bytesAvailable()){
                QByteArray ary = this->m_port->readAll();
                qDebug()<<"rec arr:"<<ary<<"ary.length: "<<ary.length();
                this->m_readBuffer.append(ary);
                int index = this->m_readBuffer.indexOf("LWS");
                //qDebug()<<"index:"<<index<<"  m_readBuffer:"<<this->m_readBuffer;
                // |多余数据|LWS|正确数据|，删除第一次LWS前的所有数据
                if(index > 0 ){
                    this->m_readBuffer.remove(0, index);
                }
                if(index == -1){
                    this->m_readBuffer.remove(0, m_readBuffer.length());
                }
                if(this->m_readBuffer.length() >= METESTATION_PROTOCOLALL_LENGTH){
                    int index = this->m_readBuffer.indexOf("LWS");
                    qDebug()<<"index:"<<index<<"  m_readBuffer:"<<this->m_readBuffer;
                    if(index >= 0){
                        QByteArray result = this->m_readBuffer.mid(index, METESTATION_PROTOCOLALL_LENGTH);
                        //qDebug()<<"result : "<<result;
                        resolveProtrocol(result);
                        this->m_readBuffer.remove(index, METESTATION_PROTOCOLALL_LENGTH);
                    }
                }
            }
        });
        return true;
    }
    return false;

}

void GroundWeatherStationForm::closeDevice()
{
    m_port->close();
}
int count = 1;
void GroundWeatherStationForm::resolveProtrocol(QByteArray ary)
{
    QString str = ary;
    QStringList protocoList = str.split(' ');
    protocol::GroundWeatherStationProtocol protocol;
    protocol.m_date = QDate::fromString(protocoList[2], "yyyy-MM-dd");
    protocol.m_time = QTime::fromString(protocoList[3], "hh:mm:ss");
    QDateTime dateTime(protocol.m_date, protocol.m_time);

    bool ok;
    protocol.m_temperature = protocoList[4].toDouble(&ok)/10;
    if(!ok)
        return;
    protocol.m_humidity = protocoList[5].toDouble(&ok)/10;
    if(!ok)
        return;
    protocol.m_pressure = protocoList[6].toDouble(&ok)/10;
    if(!ok)
        return;
    protocol.m_one_minute_maxWindSpeed = protocoList[7].toDouble(&ok)/10;
    if(!ok)
        return;
    protocol.m_one_minute_windDirection = protocoList[8].toDouble(&ok)/10;
    if(!ok)
        return;
    protocol.m_two_minute_avgWindSpeed = protocoList[9].toDouble()/10;
    protocol.m_two_minute_avgWindDirection = protocoList[10].toDouble()/10;
    protocol.m_ten_minute_avgWindSpeed = protocoList[11].toDouble()/10;
    protocol.m_ten_minute_avgWindDirection = protocoList[12].toDouble()/10;
    protocol.m_minute_precipitation = protocoList[13].toDouble(&ok)/10;
    if(!ok)
        return;
    protocol.m_hour_precipitation = protocoList[14].toDouble()/10;
    protocol.m_aux_minute_precipitation = protocoList[15].toDouble()/10;
    protocol.m_aux_hour_precipitation = protocoList[16].toDouble()/10;
    protocol.m_road_temerature = protocoList[17].toDouble()/10;
    protocol.m_atmosphere_electric_field = protocoList[18].toDouble()/10;
    protocol.m_total_solar_radiation = protocoList[19].toDouble()/10;
    protocol.m_dew_point_temperature = protocoList[20].toDouble()/10;
    protocol.m_water_vapor_pressure = protocoList[21].toDouble()/10;
    protocol.m_voltage = protocoList[22].toDouble()/10;
    protocol.m_electricity_quantity = protocoList[23].toInt();
    protocol.m_tilt_angle = protocoList[24].toDouble()/10;

    QUuid uuid = QUuid::createUuid();
    QByteArray encodedData = ary.mid(32, ary.length() - 32).toBase64();
    qDebug()<<"base64 :"<<encodedData;
    QString strSql = QString("INSERT INTO \"TESTDBA\".\"groundWeatherStation\"(\"uuid\",\"dateTime\",\"base64Data\",\"temperature\""
                             ",\"humidity\",\"pressure\",\"rain\",\"windSpeed\",\"windDirection\")"
                             "VALUES('%1','%2','%3','%4','%5','%6','%7','%8','%9');").arg(uuid.toString()).arg(dateTime.toString("yyyy/MM/dd HH/mm/ss"))
                         .arg(ary.mid(32, ary.length() - 32).toBase64()).arg(protocol.m_temperature).arg(protocol.m_humidity).arg(protocol.m_pressure)
                         .arg(protocol.m_minute_precipitation).arg(protocol.m_one_minute_maxWindSpeed).arg(protocol.m_one_minute_windDirection);
    Connection::getInstance()->update(strSql);
    qDebug()<<count++;

    emit Sig_DeviceGroundWeatherStationProtocol(protocol);
}
